package jp.gr.java_conf.genzo.wifinotify.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import android.content.Intent;
import android.os.Environment;
import android.util.Log;

public class LogUtil {

	public static boolean log = false;
	public static boolean writeTime = true;

	static private String TAG = "Log";

	private static String FILE_NAME = Environment.getExternalStorageState() +"/log.txt";

	private static PrintWriter OUT = null;

	static private final SimpleDateFormat FORMAT = new  SimpleDateFormat("yyyy/MM/dd HH:mm:ss SSS : ");

	static SimpleDateFormat mSdf = new  SimpleDateFormat("yyyyMMdd");

	static{

		init();

		//システム終了時にクローズ
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			public void run() {
				finishLog();
			}
		}));
	}

	private static void init() {

		if (log == false){
			return;
		}

		//ディレクトリの作成とか
		if(initSD()){
			//PrintWriter準備
			initLog();
		}
	}


	private static Date mCurDate = null;
	private static boolean initSD() {

		Date newDate = new Date();
//		if (mCurDate != null)
//			Log.e(TAG, "initSD = " + mCurDate.getDate() + " " + newDate.getDate());
		if (mCurDate != null && mCurDate.getDate() == newDate.getDate()){
			return false;
		}

		mCurDate = newDate;

		// 外部保存用パスの取得
		String filePath = Environment.getExternalStorageDirectory().getPath() + "/wifinotify/";
		//ファイル名の生成
		String fileName = "log" + mSdf.format(mCurDate) + ".log";
		//ファイルのフルパスを生成
		FILE_NAME = filePath + fileName;

		Log.e(TAG, "file = " + FILE_NAME);

		try {
			File dir = new File(filePath);
			if (dir.exists()) {
				//ディレクトリがあれば、当日のファイル以外削除
				String[] fileList = dir.list();
				Arrays.sort(fileList);
				if (fileList.length > 3){
					for (int i=0; i < fileList.length-3; i++){
						Log.i(TAG, "detete file = " + fileList[i]);
						new File(filePath + fileList[i]).delete();
					}
				}
			}else{
				//ディレクトリが無ければ作成する
				boolean res = dir.mkdirs();
				Log.e(TAG, "mkdirs = " + res);
			}

		} catch (Exception e) {
			Log.e(TAG, "initSD Error", e);
		}
		return true;
	}

	private static void initLog(){
		try {
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FILE_NAME, true), "UTF-8"));
			OUT = new PrintWriter(bw);
		} catch (Exception e) {
			Log.d(TAG, "Log Exception : ", e);
		}
	}

	private static void finishLog(){
		if (OUT != null){
			OUT.close();
		}
	}


	private LogUtil(){}


	public static void println(String messare){
		if (!log) return;
		init();

		try {
			if (writeTime){
				OUT.print(FORMAT.format(new Date()));
			}
			OUT.println(messare);
			OUT.flush();
		} catch (Exception e) {
			Log.d(TAG, "Log Exception ",e);
		}
	}


	public static void println(String messare, Throwable th){
		if (!log) return;
		init();

		try {
			if (writeTime){
				OUT.print(FORMAT.format(new Date()));
			}
			OUT.println(messare);
			th.printStackTrace(OUT);
			OUT.flush();
		} catch (Exception e) {
			Log.d(TAG, "Log Exception" + e);
		}
	}

	public static void println(String messare, Intent intent){
		if (!log) return;
		init();

		try {
			if (writeTime){
				OUT.print(FORMAT.format(new Date()));
			}
			OUT.println(messare);
			StringBuffer sb = new StringBuffer();
			sb.append("    intent=").append(intent).append("extract=");
			for(String key : intent.getExtras().keySet()){
				sb.append(key).append("=").append(intent.getExtras().get(key)).append(",");
			}
			OUT.println(sb);
			OUT.flush();
		} catch (Exception e) {
			Log.d(TAG, "Log Exception", e);
		}
	}

}
